package cn.xuqiudong.attachment.schedule;

import cn.xuqiudong.attachment.autoconfigure.AttachmentProperties;
import cn.xuqiudong.attachment.dao.BaseAttachmentDao;
import cn.xuqiudong.attachment.model.Attachment;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;


/**
 * 说明 :  临时态附件的清理定时器
 * @author  Vic.xu
 * @since  2019年12月12日 上午8:41:36
 */
@Component
public class AttachmentCleaner {

    @Resource
    private BaseAttachmentDao attachmentDao;

    @Autowired
    private AttachmentProperties attachmentProperties;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 凌晨四点 看海棠花未眠，定时清理附件
     * @return
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void clean() {
        if (!attachmentProperties.isCleaner()) {
            logger.info("未开启定时器清除临时附件");
            return;
        }
        logger.info("未眠之际，启动定时清除附件任务...");
        long t1 = System.currentTimeMillis();
        try {
            List<Attachment> list = attachmentDao.selectTemporaryAttachments();
            for (Attachment attachment : list) {
                File file = attachment.getRealFile();
                if (file != null && file.exists()) {
                    // 如果是个真实的文件，则删除
                    if (!file.isDirectory()) {
                        FileUtils.deleteQuietly(file);
                        logger.info("删除附件:[{}:{}]", attachment.getId(), file.getAbsolutePath());
                        //如果父目录为空，则删除
                        deleteEmpgyDirectory(file.getParentFile());
                    }
                }
                attachmentDao.delete(attachment.getId());
            }
        } catch (Exception e) {
            logger.warn("定时清除附件任务失败了....");
        } finally {
            long t2 = System.currentTimeMillis();
            logger.info("本次清除附件任务耗时 {}ms", t2 - t1);
        }
    }

    /**
     * 删除空的附件文件夹
     * @return
     */
    private void deleteEmpgyDirectory(File file) {
        if (file != null && file.list().length == 0) {
            file.delete();
            deleteEmpgyDirectory(file.getParentFile());
        }


    }
}

